#include <stdio.h>
#include <math.h>

typedef struct {
	double r, i;
} cmplx;

double real_part(cmplx c){
	return c.r;
}

double img_part(cmplx c) {
	return c.i;
}

double magnitude(cmplx c) {
	return sqrt(c.r*c.r + c.i*c.i);
}

double angle(cmplx c) {
	double ang;
	if(c.r > 0) {
		ang = atan(c.i/c.r);
	} else {
		ang = atan(c.i/c.r) + M_PI;
	}
	return ang;
}

cmplx make_from_real_img(double r, double i) {
	cmplx c;
	c.r = r;
	c.i = i;
	return c;
}

cmplx make_from_mag_ang(double r, double a) {
	cmplx c;
	c.r = r * cos(a);
	c.i = r * sin(a);
	return c;
}

cmplx add_cmplx(cmplx c1, cmplx c2) {
	return make_from_real_img(real_part(c1) + real_part(c2), img_part(c1) + img_part(c2));
}

cmplx sub_cmplx(cmplx c1, cmplx c2) {
	return make_from_real_img(real_part(c1) - real_part(c2), img_part(c1) - img_part(c2));
}

cmplx mul_cmplx(cmplx c1, cmplx c2) {
	return make_from_mag_ang(magnitude(c1) * magnitude(c2), angle(c1) + angle(c2));
}

cmplx div_cmplx(cmplx c1, cmplx c2) {
	return make_from_mag_ang(magnitude(c1) / magnitude(c2), angle(c1) - angle(c2));
}

void print_cmplx(cmplx c) {
	char *tmp1 = "c = %f\n";
	char *tmp2 = "c = %fi\n";
	char *tmp3 = "c = %f + %fi\n";
	double r = real_part(c);
	double i = img_part(c);
	if(i == 0) {
		printf(tmp1, r);
	} else if(r == 0) {
		printf(tmp2, i);
	} else {
		printf(tmp3, r, i);
	}
}

int main(int argc, char *argv[]) {
	cmplx c1 = {1, 3}, c2 = {6, 5};
	cmplx c3 = {0, 1};
	print_cmplx(add_cmplx(c1, c2));
	print_cmplx(sub_cmplx(c1, c2));
	print_cmplx(mul_cmplx(c1, c2));
	print_cmplx(div_cmplx(c1, c2));

	printf("\n");
	print_cmplx(c3);
	c3.i = 0;
	print_cmplx(c3);
	c3.r=1;
	c3.i=2;
	print_cmplx(c3);

	return 0;
}



